#pragma once
#include<iostream>
#include<cstring>
#include<unistd.h>
#include<functional>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/wait.h>    
#include<pthread.h>
#include"Log.hpp"
#include"InetAddr.hpp"
#include"Thread.hpp"
#include"ThreadPool.hpp"

using namespace log_ns;

enum
{
    SOCKET_ERROR=1,
    BAND_ERROR,
    LISTEN_ERROR
};

const static int gport=8888;
const static int gsock=-1;
const static int gblcklog=8;

using task_t=std::function<void()>;

class TcpServer
{
public:
    TcpServer(uint16_t port=gport)
        :_port(port)
        ,_listensockfd(gsock)
        ,_isrunning(false)
    {}

    void InitServer()
    {
        //创建
        _listensockfd=::socket(AF_INET,SOCK_STREAM,0);
        if(_listensockfd<0)
        {
            exit(SOCKET_ERROR);
            LOG(FATAL,"socket create error\n");
        }
        LOG(INFO,"socket create sussess,listensockfd: %d\n",_listensockfd); //3

        struct sockaddr_in local;
        memset(&local,0,sizeof(local));

        local.sin_family=AF_INET;
        local.sin_port=htons(_port);  //网络序列
        local.sin_addr.s_addr=INADDR_ANY;
        //绑定：sockfd 和 socket addr
        if(::bind(_listensockfd,(struct sockaddr*)&local,sizeof(local))<0)
        {
            LOG(FATAL,"bind error\n");
            exit(BAND_ERROR);
        }
        LOG(INFO,"bind success\n");

        // 设置监听状态 listen
        if(::listen(_listensockfd,gblcklog)<0)
        {
            LOG(FATAL,"listen error\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO,"listen success\n");
    }

    class ThreadData
    {
    public:
        int _sockfd;
        TcpServer *_self;
        InetAddr _addr;

    public:
        ThreadData(int sockfd,TcpServer *self,const InetAddr &addr):_sockfd(sockfd),_self(self),_addr(addr)
        {}
    };

    void Loop()
    {
        //signal(SIGCHLD,SIG_IGN);
        _isrunning=true;
        while(_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len=sizeof(client);
            // 获取新连接
            int sockfd=::accept(_listensockfd,(struct sockaddr*)&client,&len);
            if(sockfd<0)
            {
                //获取连接失败
                LOG(WARING,"accept error\n");
                continue;
            }
            InetAddr addr(client);
            LOG(INFO,"get a new link,client info: %s, sockfd is: %d\n",addr.AddrStr().c_str(),sockfd); //4
            //提供服务--version 0
            //Service(sockfd,addr);

            /*
            //提供服务--version 1(多进程版)
            pid_t id=fork();
            if(id==0)
            {
                //child
                ::close(_listensockfd);
                
                if(fork()>0) exit(0);

                Service(sockfd,addr);

                exit(0);
            }
            //fathre
            ::close(sockfd);
            int n=waitpid(id,nullptr,0);
            if(n>0)
            {
                LOG(INFO,"wait child success\n");
            }
            */

            /*
            //提供服务--version 2(多线程版)
            pthread_t tid;
            ThreadData *td=new ThreadData(sockfd,this,addr);
            pthread_create(&tid,nullptr,Excute,td); //新线程分离
            */

            //提供服务--version 3(线程池版) int sockfd,InetAddr addr
           task_t t=std::bind(&TcpServer::Service,this,sockfd,addr);
           ThreadPool<task_t>::GetInstance()->Equeue(t);

        }

        _isrunning=false;
    }

    static void *Excute(void *argc)
    {
        ThreadData *td=static_cast<ThreadData *>(argc);
        pthread_detach(pthread_self());
        td->_self->Service(td->_sockfd,td->_addr);
        delete td;
        return nullptr;
    }

    //提供服务
    void Service(int sockfd,InetAddr addr)
    {
        //长服务
        while(true)
        {
            char inbuffer[1024];
            ssize_t n=::read(sockfd,inbuffer,sizeof(inbuffer)-1);
            if(n>0)
            {
                inbuffer[1024]=0;
                LOG(INFO,"get from client %s, message: %s\n",addr.AddrStr().c_str(),inbuffer);
                std::string echo_string="[sever echo] # ";
                echo_string+=inbuffer;
                write(sockfd,echo_string.c_str(),echo_string.size());
            }
            else if(n==0)
            {
                LOG(INFO,"client %s quit\n",addr.AddrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR,"read error: %s\n",addr.AddrStr().c_str());
                break;
            }
        }
        ::close(sockfd);
    }

    ~TcpServer()
    {}

private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;
};